package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 筛选哪些审批是成本审批
 *
 * @author Administrator
 */
@WebServlet("/siftingRequestRelatedToCostAnalysis")
public class SiftingRequestRelatedToCostAnalysis extends AbstractServlet {
	
	private static final long serialVersionUID = -6524473373623928868L;
	
	private static final Logger logger = LoggerFactory.getLogger(SiftingRequestRelatedToCostAnalysis.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	/**
	 * [{"requestDkey":},{"requestDkey":}]
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			List<Request> requests = getRequests(req);
			check(requests);
			
			ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
			List<Request> costAnalysisRequests = readTemplateServicePrx.siftingRequestRelatedToCostAnalysis(requests);
			
			returnResult(resp, costAnalysisRequests);
		} catch (Throwable e) {
			onThrowable(req, resp, e);
		}
	}
	
	private List<Request> getRequests(HttpServletRequest req) throws IOException {
		String reqBody = getContent(req);
		logger.info("json参数 {}", reqBody);
		
		List<Request> requests;
		try {
			requests = JSONArray.parseArray(reqBody, Request.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RpcServerLogicalException(1, "请求格式有误");
		}
		return requests;
	}
	
	private void returnResult(HttpServletResponse resp, List<Request> result) throws IOException {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "0");
		jsonObject.put("res_info", "获得成功");
		jsonObject.put("item", result);
		
		logger.info(jsonObject.toJSONString());
		
		printJson(resp, jsonObject.toJSONString());
	}
	
	protected void check(List<Request> list) {
		if (list == null || list.size() == 0) {
			throw new RpcServerLogicalException(1, "无输入参数");
		}
	}
}
